package gu.simplemq.jms;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.activemq.jms.pool.PooledConnectionFactory;

import gu.simplemq.MQPropertiesHelper;

/**
 * @author guyadong
 *
 */
public abstract class PropertiesHelper extends MQPropertiesHelper implements JmsConstants {
	private final JmsRuntimeContext runtimeContext;
	public PropertiesHelper(JmsRuntimeContext runtimeContext) {
		this.runtimeContext = runtimeContext;
	}	

	@Override
	public void checkConnect(Properties input,Integer timeoutMills) throws JMSException{
		Properties props = initParameters(input);
		String connectTimeout = getConstProvider().getMainConnectTimeout();
		if(timeoutMills != null && timeoutMills > 0 && connectTimeout != null){
			props.setProperty(connectTimeout, timeoutMills.toString());
		}
	    PooledConnectionFactory facetory = runtimeContext.createPooledConnectionFactory(props);
	    try {
	    	Connection connect = facetory.createConnection();
	    	connect.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
	    } finally{
	    	// connect,session会在factory关闭时关闭，不需要显式调用
	    	facetory.stop();
	    }

	}

	public boolean testConnect(Properties props,Integer timeoutMills){
		try {
			checkConnect(props,timeoutMills);
			return true;
		} catch (JMSException je) {	      
		      return false;
		}
	}
}
